<script setup>
import { useRouter, useRoute } from 'vue-router'
import { GET, POST, PUT, DELETE } from '../../../api/index'
import { ref, getCurrentInstance, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Delete, Download, Upload, EditPen } from '@element-plus/icons-vue'


//分页查询
let tableData = ref([]),total = ref(0)

let size = ref(10), currentPage = ref(1)

//修改当前页
function currentChange(_page){
  currentPage.value = _page
  getList()
}

//修改每页大小
function sizeChange(_size){
  size.value = _size
  currentPage.value = 1
  getList()
}

let userName = ref('')

async function getList() {
  let res = await GET('http://localhost:9999/User/selectPage', { userName:userName.value, page:currentPage.value,size:size.value })
  console.log(res)
  tableData.value = res.data.list
  total.value = res.data.total
}

let dialogFormVisible = ref(false)

let defaultForm = {
  "userId": "",
  "userName": "",
  "userSex": "",
  "userAge": "",
  "address": "",
  "userCarid": "",
  "phone": "",
  "email": "",
  "nation": "",
  "positionName": "",
  "positionId": "",
  "departmentId": "",
  "userSalary": "",
  "entryTime": "",
  "status": "1",
} 


//新增&修改
let formRef = ref(null)

let positionId = ref("")

let form = ref({
  
})

function addOpen(row){
  dialogFormVisible.value = true
  form.value = Object.assign(row ? row : defaultForm)
}

function submit(){
  form.value.postitionId = positionId.value
  formRef.value.validate(async(valid, fields) => {
    if(valid){
      let res
      if(!form.value.userId){
        res = await POST('http://localhost:9999/User/add', form.value)
      }else{
        res = await PUT('http://localhost:9999/User/update', form.value)
        console.log(form.value)
      }
      if(res.code == 200 && res.data == 1) {
        ElMessage.success(form.value.userId ? '修改成功' : '新增成功')
        dialogFormVisible.value = false
        currentPage.value = 1
        await getList()
      } 
    }
  })
}

let formRule = {
  userName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
  ],
  userSex: [
    { required: true, message: '请选择性别', trigger: 'change' },
  ],
  userCarid: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
  ],
}


//删除
async function deleteUser(id) {
  console.log(id)
  let res = await DELETE('http://localhost:9999/User/delete', {userId:id})
  if (res.data.num != 0) {
    ElMessage.success("删除成功")
    await getList()
  }
}


//文件导入导出
async function exp() {
  const response = await fetch("http://localhost:9999/User/export");
  const blob = await response.blob();
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.style.display = 'none';
  a.href = url;
  a.download = '员工信息.xlsx'; // 设置下载文件名
  document.body.appendChild(a);
  a.click();
  window.URL.revokeObjectURL(url);
}

async function handleExcelImportSuccess() {
  this.$message.success("文件导入成功!")
  this.load()
}


//查询所有职位作为下拉框
let positionOptions = ref([])
  async function deupdate() {
    let res = await GET('http://localhost:9999/Position/select')
    console.log(res)
    positionOptions.value = res.data
  }

onMounted(async () => {
  await getList()
  await deupdate()
})

</script>


<template>
  <div style="padding: 16px;">

    <!-- 搜索新增栏 -->
    <el-form label-width="auto" style="display: flex;">
      <el-input v-model="userName" style="width: 240px;height: 32px;" placeholder="请输入搜索内容" :prefix-icon="Search"/>
      <el-form-item style="margin-left: 16px;">
        <el-button type="primary" :icon="Search" @click="getList()">搜索</el-button>
      </el-form-item>
      <el-form-item style="margin-left: 16px;">
        <el-button type="primary" :icon="Plus" @click="addOpen()">新增</el-button>
      </el-form-item>
      <el-form-item style="margin-left: 16px;">
        <el-upload
          action="http://localhost:9999/User/import"
          :show-file-list="false"
          accept="xlsx"
          :on-success="handleExcelImportSuccess"
          style="display: inline-block">
          <el-button type="success" :icon="Download" class="ml-5">导入 <i class="el-icon-bottom"></i></el-button>
        </el-upload>
      </el-form-item>
      <el-form-item style="margin-left: 16px;">
        <el-button type="success" :icon="Upload" @click="exp" class="ml-5">导出 <i class="el-icon-top"></i></el-button>
      </el-form-item>
    </el-form>



    <!-- 列表 -->
    <el-table :data="tableData" style="width: 100%;">
      <el-table-column prop="userId" label="员工id" width="80"/>
      <el-table-column prop="userName" label="姓名" width="100"/>
      <el-table-column prop="userSex" label="性别" width="80"/>
      <el-table-column prop="userAge" label="年龄" width="80"/>
      <el-table-column prop="address" label="地址" width="100"/>
      <el-table-column prop="userCarid" label="身份证号" width="100"/>
      <el-table-column prop="phone" label="手机号" width="100"/>
      <el-table-column prop="email" label="邮箱" width="100"/>
      <el-table-column prop="positionName" label="职位名称" width="100"/>
      <el-table-column prop="userSalary" label="薪资" width="100"/>
      <el-table-column prop="entryTime" label="入职时间" width="100"/>
      <el-table-column label="操作" width="200" >
        <template #default="scope">
          <el-button type="success" :icon="EditPen" style="width: 50px;" @click="addOpen(scope.row)"></el-button>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="#626AEF"
            title="确定删除" @confirm="() => deleteUser(scope.row.userId)">
            <template #reference>
              <el-button type="danger" :icon="Delete" style="width: 50px;"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页样式 -->
    <div style="display: flex;justify-content: flex-end;margin-top: 16px;">
      <el-pagination
        @size-change="sizeChange"
        @current-change="currentChange" 
        :current-page="currentPage" 
        :page-sizes="[3, 5, 8, 10, 20, 100, 200, 300, 400]" 
        :page-size="size" 
        layout="total, sizes, prev, pager, next" 
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 新增弹窗 -->
    <el-dialog v-model="dialogFormVisible" :title="form.userId ? '修改' : '新增'" width="500">
      <el-form ref="formRef" :model="form" :rules = "formRule">
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="form.userName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="性别" prop="userSex">
          <el-radio v-model="form.userSex" label="男">男</el-radio>
          <el-radio v-model="form.userSex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="年龄" prop="userAge">
            <el-input v-model="form.userAge" autocomplete="off" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
            <el-input v-model="form.address" autocomplete="off" />
        </el-form-item>
        <el-form-item label="身份证号" prop="userCarid">
            <el-input v-model="form.userCarid" autocomplete="off" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" autocomplete="off" />
        </el-form-item>
        <el-form-item label="职位选择" prop="positionName">
            <div style="display: flex;">
              <el-input v-model="positionId"></el-input>
  
              <el-select v-model="positionId" clearable placeholder="Select" style="width: 280px">
                <el-option v-for="item in positionOptions" :key="item.positionId" :label="item.positionName"
                  :value="item.positionId">
                </el-option>
              </el-select>
            </div>
          </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
 

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>